package com.hjw.dynamicdatasource.config;


import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author ivan
 */
@Configuration
@MapperScan({"com.hjw.dynamicdatasource.mapper"})
public class MyBatisPlusConfig {
    @Autowired
    private DynamicDataSourceManager dynamicDataSourceManager;
    @Autowired
    private MybatisPlusProperties mybatisPlusProperties;
    
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        // 关键：使用动态数据源
        sessionFactory.setDataSource(new DynamicRoutingDataSource(dynamicDataSourceManager));
        
        // 设置类型别名包，包括动态生成的实体类包路径
        sessionFactory.setTypeAliasesPackage("com.hjw.dynamicdatasource.entity,com.hjw.dynamicdatasource.entity.dynamic");
        
        // 设置mapper位置
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:/mapper/**/*.xml"));
        
        // 配置MyBatis全局设置
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setJdbcTypeForNull(JdbcType.NULL);
        // 下划线转驼峰
        mybatisConfiguration.setMapUnderscoreToCamelCase(true);
        // 允许 JDBC 支持自动生成主键
        mybatisConfiguration.setUseGeneratedKeys(true);

        sessionFactory.setConfiguration(mybatisConfiguration);

        // 配置 MyBatis-Plus 全局配置（核心：启用 CRUD 自动生成）
        GlobalConfig globalConfig = mybatisPlusProperties.getGlobalConfig();
        sessionFactory.setGlobalConfig(globalConfig);

        return sessionFactory.getObject();
    }
    
    /**
     * 自定义配置
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
            configuration.setUseGeneratedKeys(true);
            configuration.setMapUnderscoreToCamelCase(true);
        };
    }
}